from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from redis import StrictRedis
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

# /GET /orders/
from goods.models import SKU
from orders.serializers import OrderSerializer, OrderCreateSerializer


class OrderView(APIView):
    """提交订单页面数据获取"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取相应数据并返回
        user = request.user
        # 获取用户购物车中选中的商品
        conn = get_redis_connection('cart')  # type: StrictRedis
        selected_key = 'selected_%s' % user.id
        sku_ids = conn.smembers(selected_key)
        # ('sku_id'......)

        # 获取购物车中相应的商品数量
        key = 'cart_%s' % user.id
        res_dict = conn.hgetall(key)
        # {
        #     'sku_id': count,
        #     ......
        # }
        freight = Decimal(10)
        res_list = []

        skus = SKU.objects.filter(id__in=sku_ids)

        # 转换类型,需要使用新的字典来构造,不能修改原来的字典的数据类型,会报错
        data_lict = {}
        for sku_id, count in res_dict.items():
            data_lict[int(sku_id)] = int(count)

        for sku in skus:
            if sku.id in data_lict:
                sku.count = data_lict[sku.id]
                res_list.append(sku)
        serializer = OrderSerializer(res_list, many=True)

        res_dict = {
            'freight': freight,
            'skus': serializer.data
        }
        return Response(res_dict)


class OrderCreateView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderCreateSerializer

    """订单创建"""
    # 接受参数并校验
    # 保存订单信息
    # 清除redis中购物车信息
    # 返回应答
    def post(self, request):
        # 接受参数并校验
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 保存订单信息
        serializer.save()
        # 清除redis中购物车信息
        # 返回应答
        return Response(serializer.data)
